// 引入React及相关Hooks
import React, { useCallback, useEffect, useRef, useState } from 'react';
// 引入React Native的基础组件和API
import { View, Text, TouchableOpacity, StyleSheet, Alert, TextInput } from 'react-native';
// 引入React Navigation的hook，用于页面跳转
import { useNavigation } from '@react-navigation/native';
// 引入react-native-vision-camera的组件和类型
import { Camera, CameraPermissionStatus, useCameraDevices, CameraRuntimeError } from 'react-native-vision-camera';
// 引入文件系统库，用于读取图片为base64
import RNFS from 'react-native-fs';
// 引入人脸录入API方法
import { faceAdd } from '../../ulits/instance';
// 引入屏幕适配工具
import Adapt, {
  adapt,
  adaptFontSize,
  getScreenWidth,
  getScreenHeight,
  getStatusBarHeight,
} from '../../ulits/Adapt';

// 获取屏幕宽高与状态栏高度
const SCREEN_WIDTH = getScreenWidth();
const SCREEN_HEIGHT = getScreenHeight();
const STATUS_BAR_HEIGHT = getStatusBarHeight();

// 定义FaceRegistration组件
export default function FaceRegistration() {
  // 获取导航对象
  const navigation = useNavigation();
  // 创建camera组件的ref
  const camera = useRef<Camera>(null);
  // 摄像头权限状态
  const [hasPermission, setHasPermission] = useState(false);
  // 摄像头是否初始化完成
  const [isCameraReady, setIsCameraReady] = useState(false);
  // 是否正在录入中（防止重复操作）
  const [isRegistering, setIsRegistering] = useState(false);
  // 获取所有摄像头设备
  const devices = useCameraDevices();
  // 取前置摄像头
  const frontCamera = devices.find(device => device.position === 'front');

  // 检查并请求摄像头权限
  const checkPermission = useCallback(async () => {
    try {
      console.log('Checking camera permission...');
      const permission = await Camera.getCameraPermissionStatus();
      console.log('Current permission status:', permission);

      if (permission === 'granted') {
        setHasPermission(true);
        return;
      }

      if (permission === 'not-determined') {
        console.log('Requesting camera permission...');
        const newPermission = await Camera.requestCameraPermission();
        console.log('New permission status:', newPermission);
        setHasPermission(newPermission === 'granted');
      } else {
        // 权限被拒绝，弹框提示用户去设置
        Alert.alert(
          '需要相机权限',
          '请在系统设置中允许访问相机',
          [
            { text: '取消', style: 'cancel' },
            { text: '去设置', onPress: () => navigation.goBack() }
          ]
        );
      }
    } catch (error) {
      console.error('Permission check error:', error);
      Alert.alert('错误', '无法获取相机权限');
    }
  }, [navigation]);

  // 组件挂载后检查权限
  useEffect(() => {
    checkPermission();
  }, [checkPermission]);

  // 摄像头初始化回调
  const onCameraReady = useCallback(() => {
    console.log('Camera is ready');
    setIsCameraReady(true);
  }, []);

  // 摄像头错误回调
  const onError = useCallback((error: CameraRuntimeError) => {
    console.error('Camera error:', error);
    Alert.alert('错误', '摄像头初始化失败，请重试');
  }, []);

  // 文件路径转base64
  const convertToBase64 = async (path: string): Promise<string> => {
    try {
      console.log('Reading file from path:', path);
      const fileContent = await RNFS.readFile(path, 'base64'); // 读取文件
      console.log('File read successfully, base64 length:', fileContent.length);
      return fileContent;
    } catch (error) {
      console.error('Error converting to base64:', error);
      throw new Error('转换图片格式失败');
    }
  };

  // 拍照并录入流程
  const handleCapture = useCallback(async () => {
    if (!camera.current || !isCameraReady || isRegistering || !frontCamera) {
      return;
    }

    setIsRegistering(true); // 标记正在录入
    try {
      // 1. 拍照
      console.log('Taking photo...');
      const photo = await camera.current.takePhoto({
        flash: 'off',
      });
      console.log('Photo captured:', photo);

      // 2. 转base64
      const base64Data = await convertToBase64(photo.path);
      console.log('Base64 conversion completed, length:', base64Data.length);

      // 3. 调用人脸录入API
      console.log('Calling face registration API...');
      // 使用时间戳作为临时ID
      const tempId = Date.now().toString();
      const tempName = `User_${tempId}`;
      const result = await faceAdd(base64Data, tempName, tempId);
      console.log('Face registration result:', result);

      // 4. 处理结果
      if (result.success) {
        Alert.alert(
          '录入成功', 
          '人脸信息已成功录入', 
          [{ text: '确定', onPress: () => navigation.goBack() }]
        );
      } else {
        Alert.alert('录入失败', result.message || '人脸录入失败，请重试');
      }
    } catch (error: any) {
      console.error('Registration error:', error);
      Alert.alert('错误', error.message || '录入过程出错，请重试');
    } finally {
      setIsRegistering(false); // 恢复录入按钮
    }
  }, [isCameraReady, isRegistering, frontCamera, navigation]);

  // 没有权限时的提示界面
  if (!hasPermission) {
    return (
      <View style={styles.container}>
        <View style={styles.messageContainer}>
          <Text style={styles.title}>需要相机权限</Text>
          <Text style={styles.subtitle}>请在设置中允许访问相机</Text>
          <TouchableOpacity 
            style={styles.primaryBtn}
            onPress={checkPermission}
          >
            <Text style={styles.btnText}>重新获取权限</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }

  // 前置摄像头未初始化时
  if (!frontCamera) {
    return (
      <View style={styles.container}>
        <View style={styles.messageContainer}>
          <Text style={styles.title}>正在初始化</Text>
          <Text style={styles.subtitle}>正在准备摄像头...</Text>
        </View>
      </View>
    );
  }

  // 正常渲染摄像头和UI
  return (
    <View style={styles.container}>
      {/* 摄像头画面区域，做了垂直镜像 */}
      <View style={styles.cameraWrapper}>
        <Camera
          ref={camera}
          style={styles.camera}
          device={frontCamera}
          isActive={true}
          photo={true}
          onError={onError}
          onInitialized={onCameraReady}
        />
      </View>
      
      {/* UI叠加层 */}
      <View style={styles.overlay}>
        {/* 顶部提示 */}
        <View style={[styles.header, { marginTop: STATUS_BAR_HEIGHT + adapt(40) }]}>
          <Text style={styles.title}>人脸录入</Text>
          <Text style={styles.subtitle}>请将面部置于圆形框内</Text>
        </View>

        {/* 人脸引导圆环 */}
        <View style={styles.guideContainer}>
          <View style={styles.faceGuideRing} />
        </View>

        {/* 底部按钮 */}
        <View style={styles.buttonContainer}>
          <TouchableOpacity
            style={[styles.captureBtn, !isCameraReady && styles.disabledBtn]}
            onPress={handleCapture}
            disabled={!isCameraReady || isRegistering}
          >
            <Text style={styles.btnText}>
              {isRegistering ? '录入中...' : '开始录入'}
            </Text>
          </TouchableOpacity>
          
          <TouchableOpacity
            style={styles.cancelBtn}
            onPress={() => navigation.goBack()}
          >
            <Text style={styles.btnText}>返回</Text>
          </TouchableOpacity>
        </View>
      </View>
    </View>
  );
}

// 样式表
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#000', // 全黑背景
  },
  cameraWrapper: {
    width: SCREEN_WIDTH,
    height: SCREEN_HEIGHT,
    transform: [{ scaleY: -1 }], // 垂直翻转，适配前置镜像
  },
  camera: {
    width: '100%',
    height: '100%',
  },
  overlay: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: 'rgba(0,0,0,0.5)', // 半透明黑色遮罩
  },
  messageContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: adapt(20),
  },
  header: {
    alignItems: 'center',
    marginTop: STATUS_BAR_HEIGHT + adapt(40), // 增加顶部间距
  },
  title: {
    fontSize: adaptFontSize(24),
    fontWeight: 'bold',
    color: '#fff',
    marginBottom: adapt(8),
  },
  subtitle: {
    fontSize: adaptFontSize(16),
    color: '#fff',
    opacity: 0.8,
  },
  guideContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: adapt(10), // 增加圆框顶部间距
  },
  faceGuideRing: {
    width: adapt(250),
    height: adapt(250),
    borderRadius: adapt(125), // 圆形
    borderWidth: Adapt.DeviceType.isIOS ? 2 : 3,
    borderColor: '#FFD700',
    borderStyle: 'dashed',
  },
  inputContainer: {
    paddingHorizontal: adapt(40),
    marginTop: adapt(60), // 增加输入框区域顶部间距
    marginBottom: adapt(20),
  },
  input: {
    backgroundColor: 'rgba(255,255,255,0.9)',
    borderRadius: adapt(8),
    paddingHorizontal: adapt(15),
    paddingVertical: adapt(12),
    marginBottom: adapt(10),
    fontSize: adaptFontSize(16),
    color: '#000',
  },
  buttonContainer: {
    alignItems: 'center',
    paddingBottom: adapt(40), // 减少底部间距以平衡整体
  },
  captureBtn: {
    backgroundColor: '#FF9500',
    paddingHorizontal: adapt(60),
    paddingVertical: adapt(15),
    borderRadius: adapt(25),
    marginBottom: adapt(15),
    width: '85%',
    alignItems: 'center',
  },
  cancelBtn: {
    backgroundColor: 'rgba(255,255,255,0.3)',
    paddingHorizontal: adapt(60),
    paddingVertical: adapt(15),
    borderRadius: adapt(25),
    width: '85%',
    alignItems: 'center',
  },
  btnText: {
    color: '#fff',
    fontSize: adaptFontSize(18),
    fontWeight: '600',
  },
  disabledBtn: {
    opacity: 0.5,
  },
  primaryBtn: {
    backgroundColor: '#FF9500',
    paddingHorizontal: adapt(40),
    paddingVertical: adapt(12),
    borderRadius: adapt(20),
    marginTop: adapt(20),
    width: '85%',
    alignItems: 'center',
  },
});